<template>
  <section>
    <el-row style="margin: -3px 0px 0px 1px">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/system/dashboard' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户信息</el-breadcrumb-item>
      </el-breadcrumb>
    </el-row>

    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" style="float:left;margin: 18px 27px -3px">
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="batchDelete" :disabled="buttonDisabled">批量删除</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <el-card style="margin: 18px 2%;width: 95%">
      <el-table
        :data="userList"
        stripe
        :default-sort="{prop: 'id', order: 'ascending'}"
        style="width: 100%"
        @selection-change="selectChange"
        :max-height="tableHeight">
        <!--选择框-->
        <el-table-column type="selection" width="55"/>
        <!--Form-->
        <el-table-column prop="id" label="id" sortable/>
        <el-table-column prop="username" label="用户名" fit/>
        <el-table-column prop="realName" label="真实姓名" fit/>
        <el-table-column prop="gender" label="性别" :formatter="genderFormatter" fit/>
        <el-table-column prop="phone" label="手机号" fit/>
        <el-table-column prop="email" label="邮箱" show-overflow-tooltip fit/>

        <el-table-column prop="enable" label="是否启用" width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.enable"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="(value) => commitStatusChange(value, scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140">
          <template slot-scope="scope">
            <el-button
              @click="editUser(scope.row)"
              type="text"
              size="small">
              编辑
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="deleteUser(scope.row)">
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-col :span="24" class="toolbar">
        <el-col :span="24" class="toolbar">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes="[5, 10, 20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </el-col>
      </el-col>
    </el-card>
    <edit-user ref="editDialog" @reload="listUser"/>
    <add-user ref="addDialog" @reload="listUser"/>
  </section>

</template>

<script>
import EditUser from "./usercomponent/EditUser";
import AddUser from "./usercomponent/AddUser";

export default {
  name: "UserProfile",
  components: {EditUser, AddUser},
  data() {
    return {
      userList: [],
      dialogFormVisible: false,
      roles: null,
      size: 5,
      total: 0,
      page: 1,
      username: '',
      checked: [],
      buttonDisabled: true
    }
  },

  mounted() {
    this.listUser();
    this.currentRoles();
  },

  computed: {
    tableHeight() {
      return window.innerHeight - 320
    }
  },

  methods: {
    /*
    * 当前登录用户拥有的权限
    * */
    currentRoles() {
      var currentRoles = this.$store.state.currentRole
      for (let currentRolesKey in currentRoles) {
        this.roles = currentRoles[currentRolesKey]
      }
      return this.roles
    },
    listUser() {
      this.$axios.post('/system/users', {
        page: this.page,
        size: this.size,
        username: this.username
      }).then(resp => {
        if (resp.status === 200 && resp) {
          this.userList = resp.data.result;
          this.total = resp.data.total
        }
      })
    },
    handleAdd(){
      this.$refs.addDialog.dialogFormVisible = true
    },
    /*
    * 性别格式化
    * */
    genderFormatter(row) {
      if (row.gender === '1') {
        return "男"
      }
      if (row.gender === '2') {
        return "女"
      }
    },
    editUser(user) {
      var role = this.roles
      // this.$nextTick(()=>{
      this.$refs.editDialog.edit(user, role)
      this.$refs.editDialog.title = '用户修改表单'
      this.$refs.editDialog.selectedRolesIds = []
      // })
    },
    deleteUser(row) {
      this.$confirm('确认删除该用户吗','警告',{
        confirmButtonText:'确定',
        cancelButtonText:'取消',
        type:"warning"
      }).then(()=>{
        var role = this.roles
        var selectRole
        this.$axios.post('/role/selectedUserRoles', row).then(resp => {
          var result = resp.data.result
          for (let resultKey in result) {
            selectRole = result[resultKey].name
          }
          if (role === 'superAdmin') {
            this.ifdelete(row)
          }
          if (role === 'sysAdmin' && selectRole !== 'superAdmin' && selectRole !== 'sysAdmin') {
            this.ifdelete(row)
          } else if (role === 'userManager' && selectRole !== 'sysAdmin' && selectRole !== 'superAdmin') {
            this.ifdelete(row)
          } else {
            this.$message({message: '对不起,您没有权限', type: "error"})
          }
        })
      })
    },
    ifdelete(row) {
      this.$axios.post('/system/user/delete', row).then(resp => {
        if (resp.data.code === 200) {
          this.$message({
            message: '用户[' + row.username + ']已删除',
            type: "warning"
          })
          this.listUser()
        } else {
          this.$message({
            message: '用户[' + row.username + ']删除失败',
            type: "error"
          })
          this.listUser()
        }
      })
    },
    commitStatusChange(value, user) {
      // 如果是超级管理员，拥有绝对权限
      if (this.$store.state.username === 'superAdmin') {
        this.$axios.put('/system/user/changeEnable', {
          enable: value,
          id: user.id
        }).then(resp => {
          if (resp.data.code === 200) {
            if (value) {
              this.$message({
                message: '用户 [' + user.username + '] 已启用',
                type: "success"
              })
            } else {
              this.$message({
                message: '用户 [' + user.username + '] 已禁用',
                type: "warning"
              })
            }
          }
        })
      }
      // 拿到用户信息先去判断是否有管理员权限
      this.$axios.get('/system/user/isAdmin/' + user.id).then(resp => {
        var respdata = resp.data.result
        var selectUserRole = null
        for (var respdataKey in respdata) {
          selectUserRole = respdata[respdataKey]
        }
        if (selectUserRole !== 'sysAdmin' || selectUserRole !== 'superAdmin' || selectUserRole === null) {
          this.$axios.put('/system/user/changeEnable', {
            enable: value,
            id: user.id
          }).then(resp => {
            if (resp.data.code === 200) {
              if (value) {
                this.$message({
                  message: "用户[" + user.username + "] 已启用",
                  type: "success"
                })
              } else {
                this.$message({
                  message: "用户[" + user.username + "] 已禁用",
                  type: "warning"
                })
              }
            }
          })
        } else {
          user.enable = true
          this.$alert('不能禁用管理员账户')
        }
      })
    },
    batchDelete() {
      this.$confirm("确认批量删除数据吗？", "警告", {
        type: "warning"
      }).then(() => {
        var row = this.checked;
        /*
        * 1.拿到选中的每个角色
        * 2.判断角色中是否有管理员或者超级管理员
        * 3.如果是管理员或者超级管理员权限则进行提示
        * 4.
        * */
        for (let i = 0; i < row.length; i++) {
          this.$axios.post('/role/selectedUserRoles', row[i]).then(resp => {
            var selectUser = []
            var selectRole
            var result = resp.data.result
            var selectedRow = row
            for (let resultKey in result) {
              selectRole = result[resultKey].name
            }
            if (selectRole === 'sysAdmin' || selectRole === 'superAdmin') {
              selectUser.push(row[i].username)
              this.$message({
                message: "你没有权限删除" + selectUser,
                type: "warning"
              })
              selectedRow = row.splice(row.splice(i, 1))
              this.$axios.post("/system/user/batchDelete/", selectedRow).then((resp) => {
                if (resp.data.code === 200) {
                  this.$message({
                    message: '删除成功',
                    type: 'success'
                  });
                  this.listUser();
                } else {
                  this.$message.error("删除失败")
                }
              });
            } else {
              this.$axios.post("/system/user/batchDelete/", selectedRow).then((resp) => {
                if (resp.data.code === 200) {
                  this.$message({
                    message: '删除成功',
                    type: 'success'
                  });
                  this.listUser();
                } else {
                  this.$message.error(resp.data.msg)
                }
              });
            }
          })
        }
      }).catch(() => {
      });
    },
    selectChange(checked) {
      console.log(checked.length)
      if (checked.length >= 1) {
        this.buttonDisabled = false
      }
      if(checked.length<1)
        this.buttonDisabled = true
      this.checked = checked
    },
    handleCurrentChange(page) {
      this.page = page
      this.listUser()
    },
    handleSizeChange(val){
      this.size = val
      this.listUser()
    }
  }
}
</script>

<style scoped>

</style>
